<?php
/**
 *
 * Author:苏光盼
 * Date:2020/5/21 下午4:26
 * Class:Set.php
 * Web:https://zoodt.com
 * Project:在线工具
 *
 *
 *
 */

namespace App\Model;


use App\Util\Common;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\ORM\AbstractModel;

class Config extends AbstractModel
{
    protected $tableName = 'config';
    protected $autoTimeStamp = false;
    protected $updateTime = false;


    public function myGet( $field = '' ){
        $data = Common::redis()->get('zoodt_config_array');
        if(!$data){
            $data =  $this->_get_config();
        }
        if(is_string($field) and !empty($field)){
            if( isset($data[$field]) and isset($data[$field]['value'])){
                return $data[$field]['value'];
            }
            return null;
        } else if( is_array($field) and !empty($field)){
            $temp = [];
            foreach($field as  $k){
                $temp += [$k => $data[$k]];
            }
            return $temp;
        } elseif( empty($field) ) {
            return $data;
        }
        return null;
    }


    public  function _get_config(){
        $data = $this->field('id,value,name')->indexBy('name');
        if(!$data){
            throw new \EasySwoole\ORM\Exception\Exception('get system config err',500);
        }
        TaskManager::getInstance()->async(function () use ($data){
            Common::redis()->set('zoodt_config_array',$data);
        });
        return $data;
    }

    public static function clear_config():void{
        Common::redis()->del('zoodt_config_array');
    }
}